package org.yray.sip.visit;

import org.yray.sip.base.SipMsg;
import org.yray.sip.constant.SessionStatusEnum;
import org.yray.sip.factory.impl.ActionByeA;
import org.yray.sip.factory.inet.IAction;
import org.yray.sip.factory.inet.IStopWatchFactory;
import org.yray.sip.rtp.receive.AbstractBeanHolder;
import org.yray.sip.rtp.sender.ISipSessionCache;
import org.yray.sip.server.SipServerContext;
import org.yray.sip.server.SipSession;
import org.yray.sip.utils.IcspBeanHolder;

public class SipErrVisitor extends AbstractBeanHolder implements ISipVisitor{

    @Override
    public void doALeg(SipMsg sipMsg, SipServerContext ssc) {
        log(sipMsg.getCallId(),"doALeg");
        SipSession sipSession= IcspBeanHolder.getBean(ISipSessionCache.class).get(sipMsg.getCallId());
        if(sipSession==null) {
            log(sipMsg.getCallId(),"session has bean clean");
            return;
        }
        else if(sipSession.getStatus().get()!= SessionStatusEnum.CLOSE) {
            sipSession.getStatus().set(SessionStatusEnum.CLOSE);
            IcspBeanHolder.getBean(IStopWatchFactory.class).periodStart(sipSession, sipMsg.getSipCode().getDisplayName());
            getEventFactory().sipEvent(sipMsg.getCallId(), sipMsg.getSipCode());
        }
        else {
            log(sipMsg.getCallId(),"session has bean close");
            return;
        }
    }

    @Override
    public void doBLeg(SipMsg sipMsg, SipServerContext ssc) {
        log(sipMsg.getCallId(),"doBLeg");
        SipSession sipSession=IcspBeanHolder.getBean(ISipSessionCache.class).get(sipMsg.getCallId());

        if(sipSession==null) {
            log(sipMsg.getCallId(),"session has bean clean");
        }
        else if(sipSession.getStatus().get()!=SessionStatusEnum.CLOSE)
        {
            sipSession.getStatus().set(SessionStatusEnum.CLOSE);
            IAction action = IcspBeanHolder.getBean(ActionByeA.class);
            action.action(sipMsg);
            //这里要用ALeg的
            String aId=getIdRuleComponent().getAIdFromAOrBId(sipMsg.getCallId());
            SipSession aSipSession=IcspBeanHolder.getBean(ISipSessionCache.class).get(aId);
            IcspBeanHolder.getBean(IStopWatchFactory.class).periodStart(aSipSession, sipMsg.getSipCode().getDisplayName());
            getEventFactory().sipEvent(sipMsg.getCallId(), sipMsg.getSipCode());
        }
        else
        {
            log(sipMsg.getCallId(),"session has bean close");
        }

    }
}
